package cn.lzh.controller;

import cn.lzh.entity.Order;
import cn.lzh.entity2.OrderLine;
import cn.lzh.service.OrderService;
import cn.lzh.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/adm/order")
public class OrderAdmController {
    @Autowired
    private OrderService orderService;

   //添加快递
    @RequestMapping("/addShip")
    public Map<String, Object> Addrship(@RequestBody Order ord) {
       orderService.updateOrdShip(ord);
        System.err.println(ord);
        return RespJson.pack(200, "添加快递成功 ......", null);
    }

   //分页
    @PostMapping("/findOrdInfo/{start}/{num}")
    public Map<String, Object> findAllOrdersByUid(Integer ispay, Date tstart, Date tend, String account, String phone, String nickname, @PathVariable("start") int start, @PathVariable("num") int num) {
        Map<String, Object> info = new HashMap();
        Map<String, Object> map = new HashMap();
        map.put("startpage", start * num);
        map.put("pagenum", num);
        if (account != null) {
            map.put("account", account);
        }

        if (phone != null) {
            map.put("phone", phone);
        }

        if (nickname != null) {
            map.put("nickname", nickname);
        }

        if (ispay != null) {
            map.put("ispay", ispay);
        }

        if (tstart != null) {
            map.put("tstart", tstart);
        }

        if (tend != null) {
            map.put("tend", tend);
        }

        System.out.println("/findOrdInfo/{start}/{num} 参数:" + map.toString());

        try {
            List<OrderLine> lst = orderService.findOrdLines(map);
            info.put("total", orderService.getCount(map));
            info.put("orders", lst);
        } catch (Exception e) {
            e.printStackTrace();
            return RespJson.pack(500, "查询数据有误....", (Object)null);
        }

        return RespJson.pack(200, "", info);
    }


     //根据订单号获取该订单明细及书本信息
    @RequestMapping("/findItemInfoByOrdid/{ordid}")
    public Map<String, Object> findOrdItemInfo(@PathVariable("ordid") int ordid) {
        List<Map<String, Object>> lst = orderService.findItemInfoByOrdid(ordid);
        return RespJson.pack(200, "", lst);
    }


    /**
     * 自动转换日期类型的字段格式
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

}
